package handlers

import (
    "context"
    "log"

    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
    pb "your_project/proto"
    "your_project/world"
)

// WorldHandler 处理世界相关请求
type WorldHandler struct {
    pb.UnimplementedWorldServiceServer
}

// NewWorldHandler 创建世界处理器实例
func NewWorldHandler() *WorldHandler {
    return &WorldHandler{}
}

// PlayerLogin 处理玩家登录到世界服务器
func (h *WorldHandler) PlayerLogin(ctx context.Context, req *pb.PlayerLoginRequest) (*pb.CommonResponse, error) {
    log.Printf("Player %d logged into world server", req.PlayerId)
    
    // 通知世界管理器玩家登录
    err := world.GetWorldManager().PlayerLogin(req.PlayerId, req.Name, req.SceneId, req.Position)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to process player login: %v", err)
    }
    
    return &pb.CommonResponse{
        Success: true,
        Message: "Player logged in successfully",
    }, nil
}

// PlayerLogout 处理玩家从世界服务器登出
func (h *WorldHandler) PlayerLogout(ctx context.Context, req *pb.PlayerLogoutRequest) (*pb.CommonResponse, error) {
    log.Printf("Player %d logged out from world server", req.PlayerId)
    
    // 通知世界管理器玩家登出
    err := world.GetWorldManager().PlayerLogout(req.PlayerId, req.SceneId)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to process player logout: %v", err)
    }
    
    return &pb.CommonResponse{
        Success: true,
        Message: "Player logged out successfully",
    }, nil
}

// PlayerMove 处理玩家移动
func (h *WorldHandler) PlayerMove(ctx context.Context, req *pb.PlayerMoveRequest) (*pb.CommonResponse, error) {
    // 更新玩家位置
    err := world.GetWorldManager().PlayerMove(req.PlayerId, req.SceneId, req.Position)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to process player move: %v", err)
    }
    
    return &pb.CommonResponse{
        Success: true,
        Message: "Player moved successfully",
    }, nil
}

// GetSceneInfo 获取场景信息
func (h *WorldHandler) GetSceneInfo(ctx context.Context, req *pb.GetSceneInfoRequest) (*pb.SceneInfo, error) {
    // 获取场景信息
    sceneInfo, err := world.GetWorldManager().GetSceneInfo(req.SceneId, req.PlayerId)
    if err != nil {
        return nil, status.Errorf(codes.NotFound, "Scene not found: %v", err)
    }
    
    return sceneInfo, nil
}    